<template>
  <div>
    <!-- 先通过axios请求list的数据，然后引入表格组件，将list传递给子组件。运用插槽，使表头和表单可以自定义 -->
    <MyTable :list="list">
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template v-slot:body="{row}">
           <td>{{row.id}}</td>
        <td>{{row.goods_name}}</td>
        <td>{{row.goods_price}}</td>
        <td>
        <input
          class="tag-input form-control"
          style="width: 100px;"
          type="text"
          v-if="row.inputVisible"
          v-fff
          @blur="row.inputVisible=false"
          v-model="row.inputValue"
          @keydown.esc="row.inputValue=''"
          @keydown.enter="enterFn(row)"
          />
          <button 
          v-else 
          style="display: block;" 
          class="btn btn-primary btn-sm add-tag"
          @click="row.inputVisible = true"
          >+Tag</button>
        <span v-for="(str,index) in row.tags"
        :key="index"
        class="badge badge-warning">{{str}}</span></td>
        <!-- 点击按钮，触发删除事件，将此项的id传递给函数，遍历数组，过滤id与参数相同的项 -->
        <td> <button @click="delFn(row.id)" class="btn btn-danger btn-sm">删除</button></td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "../components/MyTable";

export default {
  components: {
    MyTable,
  },
  methods: {
    delFn(id) {
   this.list = this.list.filter(item => item.id !== id);
  },
   enterFn(row){
      if(row.inputValue.trim() === ""){
        alert('输入的内容不能为空')
        return
      }
      row.tags.push(row.inputValue)
      row.inputValue=''
   }
  },
  directives: {
    fff:{
      inserted(el){
        el.focus();
      }
    }
  },
  data() {
    return {
      list: [] // 所有数据
    };
  },
   created () {
    this.$axios({
      url : "/api/goods"
    }).then(res=>this.list=res.data.data)
    .catch(err=>console.log(err))
  },
};
</script>